#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time    : 2021/3/4 6:00 下午
# @Author  : 白辉东
# @Email   : xyxk-huidong.bai@ximalaya.com
# @File    : rtosLogCatchTools.py
# @Software: PyCharm

import threading
import time
import serial
import serial.tools.list_ports
import logging.config
from config import projectPath


# 加载配置文件
logging.config.fileConfig(projectPath.LOG_CONFIG_DIR)
logger = logging.getLogger('my_logger')

global serial_log


def write_log(com):
    """
    :param com: 单串口端口参数
    :return:
    """
    global serial_log
    log_path = projectPath.RTOS_CASH_LOG_DIR
    logger.info('存入缓存文件%s中...' % log_path)

    # 打开串口
    try:
        serial_log = serial.Serial(com, '115200', timeout=4)
    except Exception as ex:
        logger.error('读取串口%s失败，请检查!' % com)
        logger.exception(ex)

    t_catch_log = threading.currentThread()
    with open(log_path, 'a+', encoding='UTF-8') as fp:
        while getattr(t_catch_log, "open", True):
            line = serial_log.readline().strip()
            log = line.replace(b'\\\\x', b'%').decode('UTF-8', 'ignore')
            if len(log) or not (log is None):
                print(log)
                fp.write(log + '\r')

    serial_log.close()
    logger.info('读取串口日志成功!')


# 清除缓存日志
def clear_cash_log():
    try:
        with open(projectPath.RTOS_CASH_LOG_DIR, 'r+', encoding='UTF-8') as f:
            f.truncate()
            logger.info('清除缓存日志成功...')
    except Exception as e:
        logger.error('清除缓存日志失败，请检查！')
        logger.exception(e)


def test_print(sn):
    t_catch_log = threading.currentThread()
    while getattr(t_catch_log, "open", True):
        print(sn + '==========')
        time.sleep(1)
